<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2019-12-31
 * Time: 16:25
 */

namespace app\api\controller\v1;

use app\api\model\MdbUser;
use app\api\model\WechatUser;
use app\api\service\Wechat as WechatService;
use app\api\validate\CheckPhone;
use app\lib\exception\ParameterException;
use think\Controller;
use think\facade\Request;

class Wechat extends Controller
{
    /**
     * 验证
     */
    public function checkWechat()
    {
        $info = new WechatService();
        return $info->get();
    }

    // 获取openid
    public function getUser()
    {
        $post = Request::post();
        if($post['code']) {
            $url = sprintf("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
                config('wechat.app_id'),config('wechat.app_secret'),$post['code']);
            $wxResult = curl_get($url);
            $loginFail = array_key_exists('errcode',$wxResult);
            if($loginFail)
            {
                throw new ParameterException([
                    'msg' => [
                        'user' => '授权失败请重新进入!'
                    ]
                ]);
            }
            return $wxResult;
        } else {
            throw new ParameterException([
                'msg' => [
                    'user' => '授权失败请重新进入'
                ]
            ]);
        }
    }

    // 绑定电话和密码
    public function updateUser($openid,$phone,$password)
    {
        $userInfo = MdbUser::where('openid',$openid)->find();
        if(!$userInfo) {
            throw new ParameterException([
                'msg' => [
                    'user' => '授权失败请重新进入'
                ]
            ]);
        }
        if($userInfo['status'] == 2) {
            throw new ParameterException([
                'msg' => [
                    'user' => '信息已同步'
                ]
            ]);
        }
        (new CheckPhone())->goCheck();
        $userInfoOne = MdbUser::where('phone',$phone)
            ->find();
        if($userInfoOne) {
            if($userInfoOne['id'] != $userInfo['id']) {
                throw new ParameterException([
                    'msg' => [
                        'user' => '该手机号已有人绑定请重新输入'
                    ]
                ]);
            }
        }
        MdbUser::where('id',$userInfo['id'])->update([
            'phone' => $phone,
            'password' => $password,
        ]);
        return writeJson(202, [], '提交成功！');
    }
}